use std::io::prelude::*;
use std::net::{TcpListener, TcpStream};
// use std::io::{Read, Write};
use std::fs;


fn main() {
    println!("Hello, world!");

   let listener= TcpListener::bind("127.0.0.1:8998").unwrap();
   for stream in listener.incoming() {
       let stream=stream.unwrap();
       handle_connection(stream);
       // println!("Connection established");

   }
}

fn handle_connection(mut stream :TcpStream){
    let mut  buffer=[0;512];
    stream.read(&mut buffer).unwrap();
    // println!("Request :{}",String::from_utf8_lossy(&buffer[..]))

    let get=b"GET /HTTP/1.1 \r\n";
    let get1=buffer.starts_with(get);
    println!("{}",get1);

    if buffer.starts_with(get) {
        let contents= fs::read_to_string("hello.html").unwrap();

        let response=format!("HTTP/1.1 200 OK\r\n\r\n{}",contents);
        stream.write(response.as_bytes()).unwrap();
        stream.flush().unwrap();

        println!("contents==={}",contents);
    }else {
        let status_line="HTTP/1.1 404 FOUND\r\n\r\n";
        let contents=fs::read_to_string("404.html").unwrap();
        let response = format!("{}{}",status_line,contents);
        stream.write(response.as_bytes()).unwrap();
        stream.flush().unwrap();
        println!("contents==={}",response);
    }



    println!("{}",111);


}



